<template>
    <div class="page" style="background-color: #eeeeee;color:#000">
        <div class="header hostInfo">
            <div class="hostInfo-item">
                <span>主机名称：</span>
                <span>{{hostInfo.name}}</span>
            </div>
            <div class="hostInfo-item">
                <span>安装位置：</span>
                <span>{{hostInfo.userAddress}}</span>
            </div>
        </div>
        <div class="navbar" >
            <div class="current">当周（{{currentTimeRange}}）：{{currentTotal.toFixed(3)}}度</div>
            <div class="last">上周（{{lastTimeRange}}）：{{lastTotal.toFixed(3)}}度</div>
        </div>
        <the-bar-chart :chartData="barChartData"></the-bar-chart>
        <the-table-data :tableData="tableData"></the-table-data>
    </div>
</template>

<script>
    import req from '@/utils/ajax.js'
    import date from '@/utils/date.js'
    import TheBarChart from './components/TheBarChart'
    import TheTableData from './components/TheTableData'

    //加法避免精度丢失
    function accAdd(arg1, arg2) {
        var r1, r2, m;
        try {
            r1 = arg1.toString().split(".")[1].length
        } catch (e) {
            r1 = 0
        }
        try {
            r2 = arg2.toString().split(".")[1].length
        } catch (e) {
            r2 = 0
        }
        m = Math.pow(10, Math.max(r1, r2))
        return (arg1 * m + arg2 * m) / m
    }

    //检查日期合法性
    function checkDate(date) {
        return (new Date(date).getDate() == date.substring(date.length - 2));
    }

    // 格式化x周数据
    function formatXvalue(timeValue) {
        
        let tweek = new Date(timeValue.replace(/-/g, '/')).getDay()
        let tweekStr = '日一二三四五六'
        let formatRes = '周' + tweekStr.charAt(tweek)
        return formatRes
    }

    //日期的加减
    function calculationDate(dateData, days) {
        let MyDate = new Date(dateData)
        console.log(dateData,2,days,MyDate.getTime() + (days * 24 * 60 * 60 * 1000))
        MyDate = getFormatDate(MyDate.getTime() + (days * 24 * 60 * 60 * 1000))
       //console.log(MyDate)
        return MyDate
    }
    function getFormatDate(nowDate) {
        let date = new Date(nowDate)
        let month = date.getMonth() + 1
        let strDate = date.getDate()
        let hours = date.getHours()
        let minutes = date.getMinutes()
        let seconds = date.getSeconds()
        if (month >= 1 && month <= 9) {
            month = '0' + month
        }
        if (strDate < 10) {
            strDate = '0' + strDate
        }
        if (hours < 10) {
            hours = '0' + hours
        }
        if (minutes < 10) {
            minutes = '0' + minutes
        }
        if (seconds < 10) {
            seconds = '0' + seconds
        }
        let currentDate = date.getFullYear() + '-' + month + '-' + strDate + ' ' + hours + ':' + minutes + ':' + seconds
        // console.log(currentDate)
        return currentDate
        }
    export default {
        name: "index",
        components: {
            TheBarChart,
            TheTableData,
        },
        data() {
            return {
                hostId: 0,
                startTime: null,
                endTime: null,
                realStartTime: null,
                realEndTime: null,
                electricityQuantity: [],
                barChartData: {},
                currentTotal: 0,
                lastTotal: 0,
                nextTotal:0,
                currentTimeRange: '',
                lastTimeRange: '',
                nextTimeRange: '',
                tableData: [],
                hostInfo: {},
            }
        },
        created() {
            this.initPage()
        },
        methods: {
            initPage() {
                let winWide = document.body.clientWidth
                var rem = (winWide / 750) * 100 + 'px'
                document.documentElement.style.fontSize = rem
                // 从url获取事件id
                let url = window.location.href
                let splitParams = url.split('?')[1]
                //是否传参
                if (splitParams) {
                    let parameters = splitParams.split('&')
                    let obj = {}
                    let keyArr = []
                    for (let item of parameters) {
                        let key = item.split('=')[0]
                        let value = item.split('=')[1]
                        obj[key] = value
                        keyArr.push(key)
                    }
                    //参数合法性
                    if (keyArr.includes('id') && keyArr.includes('startTime')) {
                        this.hostId = obj.id
                        this.getHostInfo(this.hostId)
                        this.startTime =calculationDate( obj.startTime,0).slice(0, 10)
                        //日期的合法性
                        if (checkDate(this.startTime)) {
                            let days = new Date(this.startTime).getDay()
                            days = days == 0 ? -6 : -(days - 1)
                            this.realStartTime = calculationDate(this.startTime, days)
                            this.realEndTime = calculationDate(this.startTime, (6 + days)).slice(0, 10)
                            this.currentTimeRange = this.startTime + '~' + this.realEndTime
                            this.lastTimeRange = calculationDate(this.startTime, (-7 + days)).slice(0, 10)+ '~' + calculationDate(this.startTime,(-7 + 6 + days)).slice(0, 10)
                            this.getElectricityData()
                        } else {
                            this.$message({
                                message: '日期格式不符合规范，请输入日期格式为XXXX-XX-XX',
                                type: 'warning',
                            })
                        }
                    } else {
                        this.$message({
                            message: '访问的url有误，请输入相关参数【id,startTime】',
                            type: 'warning',
                        })
                    }
                } else {
                    this.$message({
                        message: '访问的url有误，请输入相关参数【id,startTime】',
                        type: 'warning',
                    })
                }
            },
            // 获取设备信息
            getHostInfo: function (hostCode) {
                let self = this
                req.get({
                    url: self.$API.getHostInfo + hostCode,
                    showLoading: false,
                    success: function (resp) {
                        self.hostInfo = resp.data
                        console.log("设备信息", resp.data)
                    },
                    error: function () {
                    },
                })
            },
            // 获取用电量和总用电量的柱形图数据
            getElectricityData: function () {
                let self = this
                let po_id = this.hostId
                let startTime = this.realStartTime.slice(0, 10) + ' ' + '00:00:00'
                let endTime = this.realEndTime.slice(0, 10) + ' ' + '23:59:59'
                req.post({
                    url: self.$API.getElectricQuantity + po_id,
                    data: {hostCode: po_id, timeRange: 'week', startTime: startTime, endTime: endTime},
                    dataType: 'json',
                    success: function (res) {
                        console.log(res)
                        self.setBarChartData(res.data)
                    },
                    showLoading: true,
                    error: function (res) {
                        console.log(res)
                    },
                })
            },
            // 设置用电量柱状图
            setBarChartData(jsonData) {
                let self = this
                if (jsonData) {
                    let jsonDataTotal = jsonData
                    console.log("处理之前", jsonData)
                    let xValueTotalList = [] //x周数据
                    let valueListCurrent = []
                    let valueListLast = []
                    let valueListNext = []
                    let seriesTotalList = []
                    valueListCurrent = new Array(7)
                    valueListLast = new Array(7)
                    valueListNext = new Array(7)
                    let currentTimeArr = []
                    let lastTimeArr = []
                    let nextTimeArr = []
                    xValueTotalList = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
                    if (jsonDataTotal.curr.length > 0) {
                        for (let item of jsonDataTotal.curr) {
                            valueListCurrent[xValueTotalList.indexOf(formatXvalue(item.time))] = item.electricQuantityTotal
                            this.currentTotal = accAdd(this.currentTotal, item.electricQuantityTotal)
                            currentTimeArr.push(item.time.slice(0, 10))
                        }
                    } else {
                        valueListCurrent = []
                    }
                    if (jsonDataTotal.last.length > 0) {
                        for (let item of jsonDataTotal.last) {
                            valueListLast[xValueTotalList.indexOf(formatXvalue(item.time))] = item.electricQuantityTotal
                            this.lastTotal = accAdd(this.lastTotal, item.electricQuantityTotal)
                            lastTimeArr.push(item.time.slice(0, 10))
                           
                        }
                        
                    } else {
                        valueListLast = []
                    }
                    // if (jsonDataTotal.next.length > 0) {
                    //     for (let item of jsonDataTotal.next) {
                    //         valueListNext[xValueTotalList.indexOf(formatXvalue(item.time))] = item.electricQuantityTotal
                    //         this.nextTotal = accAdd(this.nextTotal, item.electricQuantityTotal)
                    //         nextTimeArr.push(item.time.slice(0, 10))
                    //     }
                    // } else {
                    //     valueListLast = []
                    // }
                    this.dealTableData(xValueTotalList, valueListCurrent, valueListLast, lastTimeArr, currentTimeArr)
                    let series1Total = {
                        type: 'bar',
                        name: '上周',
                        barGap: '0%',
                        data: valueListLast, // 数据data
                        itemStyle: {
                            color: '#24a8ac',
                        },
                    }
                    seriesTotalList.push(series1Total)

                    let series2Total = {
                        type: 'bar',
                        name: '当周',
                        barGap: '0%',
                        data: valueListCurrent, // 数据data
                        itemStyle: {
                            color: '#0087cb',
                        },
                    }
                    seriesTotalList.push(series2Total)
                    // let series3Total = {
                    //     type: 'bar',
                    //     name: '当周',
                    //     barGap: '0%',
                    //     data: valueListNext, // 数据data
                    //     itemStyle: {
                    //         color: '#0087cb',
                    //     },
                    // }
                    // seriesTotalList.push(series3Total)
                    let barChartData = {}
                    barChartData.title = '一周用电量'
                    barChartData.color = ['#24a8ac', '#0087cb'],
                        barChartData.seriesData = seriesTotalList
                    barChartData.week = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
                    barChartData.echartInterval = 7
                    self.barChartData = barChartData
                }
            },
            // 设置表格数据
            dealTableData(weekArr, currentArr, lastArr, lastTimeArr, currentTimeArr) {
                let tableData = []
                let today = new Date().getTime()
                for (let i = 0; i < 7; i++) {
                    let currentDay = new Date(currentTimeArr[i]).getTime()
                    let lastDay = new Date(lastTimeArr[i]).getTime()
                    let tr = {}
                    tr['week'] = weekArr[i]
                    if (currentDay > today || currentArr[i] == undefined) {
                        tr['current'] = '--'
                    } 
                    else if(currentArr[i]=='0')
                    {
                        tr['current'] = '--'
                    }
                    else {
                        tr['current'] = currentArr[i].toFixed(1)
                    }

                    if (lastDay > today || lastArr[i] == undefined) {
                        tr['last'] = '--'
                    } 
                    else if(lastArr[i]=='0')
                    {
                        tr['last'] = '--'
                    }
                    else {
                        tr['last'] = lastArr[i].toFixed(1)
                    }
                    tableData.push(tr)
                }
                this.tableData = tableData
                console.log('表格数据', tableData)
            }
        }
    }
</script>

<style scoped lang="stylus">
    .page
        position: absolute;
        width: 100%;
        height: auto;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        background-color: #eeeeee;


        .navbar, .header
            /*width: 100%;*/
            margin: 0.2rem 0.3rem;
            height: 1rem;
            padding: 0.2rem;
            box-sizing: border-box;
            background-color: #ffffff;
            /*margin-bottom: 0.2rem;*/
            font-size: 0.24rem;
            box-shadow: 0.04rem 0.04rem 0.1rem 0 rgba(0, 0, 0, 0.1);
            border-radius: 0.1rem;

        .hostInfo-item
            margin-bottom: 0.1rem;

        .navbar .current
            margin-bottom: 0.1rem;


        .navbar .last
            color: #7d7d7d;
            font-size: 0.22rem;

>>>
    .el-loading-spinner
        background-color red!important


</style>